/**
 * @file 工单列表
 * @author yangjiangming <449654337@qq.com>
 * @date 2018/11/27 10:20:40
 */
var dependsList = [
    'element', 'layer', 'form', 'table', '$http',
    'laydate', 'tooltipster', 'zmnTable', 'oms_work_config', 'formSelects', 'zmnDate', 'NP', 'select2', 'zmnUtils', 'zmnSelect', 'zmnOmsSelect', 'oms_common_table_config'
];
layui.extend({
    oms_common_table_config: 'common/zmn.oms.common.table.config',
    oms_work_config: "work/config/zmn.oms.work.config"
}).define(dependsList, function (exports) {
    var $ = layui.$;
    var form = layui.form;
    var layer = layui.layer;
    var table = layui.table;
    var laydate = layui.laydate;
    var zmnTable = layui.zmnTable;
    let zmnOmsSelect = layui.zmnOmsSelect;
    var $http = layui.$http;
    var NP = layui.NP;
    let zmnSelect = layui.zmnSelect;
    let zmnDate = layui.zmnDate;
    var config = layui.oms_work_config;
    var tooltipster = layui.tooltipster;

    let REDISTRIBUTE_BASE_URL = OMS_BASE_URL + '/work/redistribute';
    let DISTRIBUTE_REASON_BASE_URL = OMS_BASE_URL + '/conf/distributeReason';
    let CHECK_CAN_AUDIT_URL = REDISTRIBUTE_BASE_URL + "/checkCanAudit"
    let json = {
        vo: {
            limitPermit: false,
            orgLimitPermit: dpermitOrgIdList && dpermitOrgIdList.length > 0 ? true : false, // 没有配置组织架构，不引用权限
            channelLimitPermit: false,
            companyIdOrGirdCompanyIdList: null,
            spCompanyOrGridSpCompanyIdIdList: null,
            companyIdList: null,
            spCompanyIdList: null,
            gridCompanyIdList: null,
            gridSpCompanyIdList: null,
            servCategId: null,
            bizType: null,
        }
    };

    var datePickerSelectorArray = [
        'redistributeApplyTime', // 改派发起时间
    ];

    var multipleSelectNameArray = [
        'cityIdList',
        'provinceIdList',
        'countyIdList',
        'workStatusList',
        'trackTypeId',
        'showCategOneIdList',
        'showCategTwoIdList',
        'showProductIdList',
        'categOneIdList',
        'categTwoIdList',
        'productIdList',
        'channelIdList',
        'channelTwoIdList',
        'sourceChannelIdList',
        'sourceChannelTwoIdList',
        'failMapIdList',
        'servProductGroupIdList',
        'companyIdOrGridCompanyIdList',
        'companyIdList',
        'gridCompanyIdList',
        'gridIdList',
        'tagIdList',
        'payStatusList',
        'refundWorkReviewStatusList',
        'compensateWorkReviewStatusList',
        'partakeQuotationTypeList',
        'orderPostStatusList',
        'workTypeList',
        'manageCompanyIdOrGridManageCompanyIdList',
        'manageCompanyIdList',
        'gridManageCompanyIdList'
    ];

    const LIST_REDISTRIBUTE_INFO_URL = REDISTRIBUTE_BASE_URL + '/ajax/list.action';

    /**
     * 检查是否能审核
     * @param
     */
    function checkCanAudit(params) {
        return $http.$get(CHECK_CAN_AUDIT_URL, params);
    }

    /**
     * 设置是否可以“操作按钮”的标志
     */
    function setOperationButtonFlags(data) {
        data.canAuditFlag = (data.auditStatus == 1 || data.auditStatus == 5) && data.auditType == 2 && data.redistributeStatus == 1;
        data.canAddLasterRemarkFlag = (data.auditStatus == 1 || data.auditStatus == 5) && data.redistributeStatus == 1;
        // 赋值的目的是重新渲染【操作列】的模板
        data.operation = ''
    }

    // 表格配置
    var tableConfig = {
        defaultParams: {
            // 待改派
            redistributeStatusList: [1],
            // 待审核 && 进行中
            auditStatusList: [1, 5],
            // 员工审核
            auditType: 2,
            // 发起时间（最近7天）
            redistributeApplyTime: dateFormat(new Date(new Date().getTime() - 7 * 24 * 3600 * 1000), 'yyyy/MM/dd 00:00:00') + " - " + dateFormat(new Date(), 'yyyy/MM/dd 23:59:59')
        },
        initialSearch: true,
        orderObj: {},
        config: {
            url: REDISTRIBUTE_BASE_URL + '/ajax/list.action'
        }
    };

    // 限制只能选择近365天的时间
    function render365TimeLimit(ele, staffId) {
        zmnDate.setZmnDate(ele, {
            "staffId": staffId,
            "type": "range",
            "formatStr": "yyyy/MM/dd HH:mm:ss",
            "dateType": "dateTime",
            "isInit": true,
            "rangeDays": 365
        })
    }


    /**
     * 获取改派信息数据
     */
    function getRedistributeInfoData(params) {
        return $http.ajax({
            url: LIST_REDISTRIBUTE_INFO_URL,
            type: 'post',
            dataType: 'json',
            contentType: 'application/json',
            data: JSON.stringify(params)
        });
    }

    /**
     * 更新表格单行数据
     * @param rowObj 表格数据行对象
     */
    function updateRowData(rowObj) {
        if (!rowObj) {
            return;
        }

        const currentRedistributeId = rowObj.data.redistributeId;

        getRedistributeInfoData({redistributeId: currentRedistributeId})
            .done(function (info) {
                let changeableInfo = info.data[0];

                // 设置是否可以“操作按钮”的标志
                setOperationButtonFlags(changeableInfo);

                rowObj.update(changeableInfo);
            });
    }


    /**
     * 标准化搜索参数
     * @param {object} field 参数
     */
    function normalizeSearchParams(field, formElem) {
        var params = {};

        // 整理工单号
        if (field['code'] && field['code'].length) {
            if (field['code'].length > 19) {
                field['code'] = field['code'].substring(0, 19);
            }

            if (field['code'].length === 6) {
                params['codeEnd6'] = field['code'];
                field['code'] = '';
            }
        }

        // 整理源单号
        if (field['originalId'] && field['originalId'].length) {
            if (field['originalId'].length > 19) {
                field['originalId'] = field['originalId'].substring(0, 19);
            }
        }

        // 改派缘由ID列表
        if (field['reasonIdList']) {
            field['reasonIdList'] = field['reasonIdList'].split(",");
        }

        // 业务线ID列表
        if (field['bizLineList']) {
            field['bizLineList'] = field['bizLineList'].split(",").map(value => {
                return parseInt(value);
            })
        }

        if (field['redistributeStatusList']) {
            field['redistributeStatusList'] = field['redistributeStatusList'].split(",").map(value => {
                return parseInt(value);
            })
        }

        if (field['auditStatusList']) {
            field['auditStatusList'] = field['auditStatusList'].split(",").map(value => {
                return parseInt(value);
            })
        }

        if (field['helpStatusList']) {
            field['helpStatusList'] = field['helpStatusList'].split(",").map(value => {
                return parseInt(value);
            })
        }

        // 服务分类ID列表
        if (field['servCategId']) {
            field['servCategIdList'] = field['servCategId'].split(",").map(value => {
                return parseInt(value);
            })
            delete field['servCategId'];
        }

        // 整理操作类型、操作员
        if (field['operate_operateType'] || field['operate_operatorId']) {
            params['operate'] = {
                operateType: field['operate_operateType'] || null,
                operatorId: field['operate_operatorId'] || null
            };

            field['operate_operateType'] = null;
            field['operate_operatorId'] = null;
        }


        // 拷贝非空字段
        Object.keys(field).filter((key) => {
            if (field[key]) {
                if (multipleSelectNameArray.indexOf(key) !== -1) {
                    params[key] = field[key].split(',');
                } else {
                    params[key] = field[key];
                }
            }
        });

        // 拼接渠道
        var channelIdList = params['channelIdList'] || [];
        var channelIdListOfInput = (params['channelIdListOfInput'] || '')
            .replace(/\s/g, '')
            .replace(/\，/g, ',')
            .replace(/^\,/, '')
            .replace(/\,$/, '')
            .split(',')
            .filter(function (item) {
                return !!item;
            });
        channelIdList = channelIdList.concat(channelIdListOfInput);
        if (channelIdList.length) {
            params['channelIdList'] = channelIdList;
        } else {
            delete params['channelIdList'];
        }

        return params;
    }

    /**
     * 格式化时间
     * @param date
     * @param fmt
     * @returns {void|string|*}
     */
    function dateFormat(date, fmt) {
        let o = {
            "M+": date.getMonth() + 1,                 //月份
            "d+": date.getDate(),                    //日
            "h+": date.getHours(),                   //小时
            "m+": date.getMinutes(),                 //分
            "s+": date.getSeconds(),                 //秒
            "q+": Math.floor((date.getMonth() + 3) / 3), //季度
            "S": date.getMilliseconds()             //毫秒
        };
        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (let k in o) {
            if (new RegExp("(" + k + ")").test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            }
        }
        return fmt;
    }

    /**
     * 初始化页面表单验证器
     */
    function initFormVerify() {
        form.verify({
            channelListStr: function (value) {
                value = value == null ? '' : value;
                value = $.trim(value);
                if (/[^0-9\,\，]/.test(value)) {
                    return '只能输入以逗号分隔的渠道 id';
                }
                return;
            }
        });
    }

    function openDetail(obj, title, type) {
        let detailConfig = {
            type: 2,
            content: REDISTRIBUTE_BASE_URL + '/detail.action?type=' + type + '&id=' + obj.data.redistributeId,
            title
        };
        openDetailDialog(obj, detailConfig);
    }

    function openDetailDialog(rowObj, param) {
        var defaultConfig = {
            type: 2,
            content: '/',
            title: '',
            resize: false,
            shade: [0.8, '#393D49'],
            area: ['98%', '96vh'],
            minWidth: '960px',
            success: function (layero) {
                parent.layer.setTop(layero); // 重点2
                let iframeWindow = layero.find('iframe')[0].contentWindow;
                iframeWindow.window.dataList = window.dataList;
            },
            end: function () {
                // 触发搜索事件
                updateRowData(rowObj);
            }
        };

        let normalizedConfig = Object.assign({}, defaultConfig, param)
        parent.layer.open(normalizedConfig)
    }

    /**
     * 改派状态下拉框
     * @param selectId 页面的下拉对象ID
     * @param options  自定属性
     */
    function selectRedistributeStatus(selectId, options) {
        let newOptions = zmnSelect.mergeOptions(selectId, options, {
            data: redistributeAuditStatusList,
            selectedValues: [1], //已选中值（用于回显),格式：[value1,value2],
            propMap: {  // 选项参数映射配置
                name: "value",   // 显示值
                value: "key"  // 选中值
            },
        });
        return zmnSelect.selectBox(selectId, newOptions);
    }

    /**
     * 改派状态下拉框
     * @param selectId 页面的下拉对象ID
     * @param options  自定属性
     */
    function selectAuditStatus(selectId, options) {
        let newOptions = zmnSelect.mergeOptions(selectId, options, {
            data: auditStatusList,
            selectedValues: [1, 5], //已选中值（用于回显),格式：[value1,value2],
            propMap: {  // 选项参数映射配置
                name: "value",   // 显示值
                value: "key"  // 选中值
            },
        });
        return zmnSelect.selectBox(selectId, newOptions);
    }

    /**
     * 改派求助状态下拉框
     * @param selectId 页面的下拉对象ID
     * @param options  自定属性
     */
    function selectHelpStatus(selectId, options) {
        let newOptions = zmnSelect.mergeOptions(selectId, options, {
            data: helpStatusList,
            selectedValues: [], //已选中值（用于回显),格式：[value1,value2],
            propMap: {  // 选项参数映射配置
                name: "value",   // 显示值
                value: "key"  // 选中值
            },
        });
        return zmnSelect.selectBox(selectId, newOptions);
    }

    /**
     * 初始化地址栏参数
     */
    function initRequestParams() {
        // 如果是从【派单/派单（新）】页面跳转过来的
        if (orderId && orderId != 'null') {
            tableConfig.defaultParams.orderId = orderId;
            // 删除【审核类型】和【审核状态】
            delete tableConfig.defaultParams.auditType;
            delete tableConfig.defaultParams.auditStatus;
            delete tableConfig.defaultParams.redistributeApplyTime;

            $("#orderId").val(orderId);

            // 重置【审核类型】和【审核状态】下拉框内容
            $("#select-audit-status").val("")
            $("#select-audit-type").val("")
            $("#redistributeApplyTime").val("")
            form.render("select")
        }
    }

    function openAuditDialog(obj) {
        checkCanAudit({
            redistributeId: obj.data.redistributeId
        }).then((result) => {

            // 可以被审核，跳转至【改派审核】页面
            if (result) {
                openDetail(obj, '审核', 2)
                return;
            }

            layer.msg("该改派申请已被处理", {time: 1500}, function () {
                // 触发搜索事件
                $("#query-tool button[lay-filter='submit-search']").trigger("click");
            });

        }, (error) => {
            layer.msg(error)
        });
    }

    function getSearchParams(obj) {
        var params = normalizeSearchParams(obj.field, obj.form);

        if (!Object.keys(params).length) {
            layer.msg('请至少选择一个查询条件');
            return null;
        }

        if (Object.keys(params).length <= 0) {
            layer.msg('请至少选择一个查询条件');
            return null;
        }

        return params;
    }

    /**
     * 初始化页面事件
     */
    function initEvent() {

        // 初始化生成时间选择range框
        render365TimeLimit("redistributeApplyTime", staffId)

        $('body').on('blur', 'input', function () {
            let $this = $(this);
            $this.val($this.val().replace(/(^\s*)|(\s*$)/g, ''));
        });
        // 号码处理
        $('body').on('blur', '.concat-phone', function () {
            let $concatPhone = $(this);
            if ($concatPhone.val() != $concatPhone.data('showPhone')) {
                let $cryptoPhone = $concatPhone.next();
                if ($cryptoPhone.length > 0 && $cryptoPhone.hasClass('crypto-phone')) {
                    $concatPhone.data('showPhone', '');
                    $cryptoPhone.val('');
                }
            }
        });
        $('body').on('paste', '.concat-phone', function () {
            // 粘贴处理
            let $concatPhone = $(this);
            let $cryptoPhone = $concatPhone.next();
            if ($cryptoPhone.length > 0 && $cryptoPhone.hasClass('crypto-phone')) {
                setTimeout(function () {
                    let concatPhone = $concatPhone.val();
                    if (concatPhone && concatPhone.match(/\{\s*\"show\"\s*\:\s*\"(?<show>.+)\"\s*\,\s*\"ciphertext\"\s*\:\s*\"(?<ciphertext>.+)\"\s*\}/)) {
                        let data = JSON.parse(concatPhone);
                        $concatPhone.val(data.show);
                        $concatPhone.data('showPhone', data.show);
                        $cryptoPhone.val(data.ciphertext);
                    } else if (concatPhone.indexOf('**') > 0) {
                        $concatPhone.val('');
                        $concatPhone.data('showPhone', '');
                        $cryptoPhone.val('');
                    }
                }, 20);
            }
        });

        // 监听重置按钮点击
        form.on('submit(submit-reset)', function (obj) {
            setTimeout(function () {
                clearZmnSelectedValue('companyIdOrGridCompanyIdList');
                clearZmnSelectedValue('manageCompanyIdOrGridManageCompanyId');
                clearZmnSelectedValue('manageCompanyIdOrGridManageCompanyIdList');
                clearZmnSelectedValue('companyIdList');
                clearZmnSelectedValue('manageCompanyId');
                clearZmnSelectedValue('manageCompanyIdList');
                clearZmnSelectedValue('gridCompanyIdList');
                clearZmnSelectedValue('gridManageCompanyId');
                clearZmnSelectedValue('gridManageCompanyIdList');
                clearZmnSelectedValue('provinceIdList');
                clearZmnSelectedValue('cityIdList');
                clearZmnSelectedValue('countyIdList');
                clearZmnSelectedValue('servCategId');
                clearZmnSelectedValue('categOneIdList');
                clearZmnSelectedValue('categTwoIdList');
                zmnOmsSelect.clearSelectedData('productIdList');
                zmnOmsSelect.clearSelectedData('reasonIdList');
                clearZmnSelectedValue('showCategOneIdList');
                clearZmnSelectedValue('showCategTwoIdList');
                zmnOmsSelect.clearSelectedData('showProductIdList');
                clearZmnSelectedValue('servProductGroupIdList');
                clearZmnSelectedValue('masterIds');
                clearZmnSelectedValue('cancelLiableMasterId');
                clearZmnSelectedValue('recommenderId');
                clearZmnSelectedValue('auditerId');
                clearZmnSelectedValue('channelTwoIdList');
                clearZmnSelectedValue('channelIdList');
                clearZmnSelectedValue('sourceChannelTwoIdList');
                clearZmnSelectedValue('sourceChannelIdList');
                zmnOmsSelect.clearSelectedData('gridIdList');
                zmnOmsSelect.clearSelectedData('workResultStatus');
                zmnOmsSelect.clearSelectedData('workStatusList');
                zmnOmsSelect.clearSelectedData('workTypeList');
                zmnOmsSelect.clearSelectedData('tagIdList');
                zmnOmsSelect.clearSelectedData('payStatusList');
                zmnOmsSelect.clearSelectedData('workCancelResultStatus');
                zmnOmsSelect.clearSelectedData('workCancelStatusList');
                zmnOmsSelect.clearSelectedData('refundType');
                clearZmnSelectedValue('operate_operatorId');
                clearZmnSelectedValue('cancelerId');

            }, 100);

            return true;
        });

        /**
         * 双击行 - 打开改派【审核、详情】优先打开【审核】其次【详情】
         */
        table.on('rowDouble(zmn-work-table)', function (rowObj) {
            if (rowObj.data.canAuditFlag) {
                openAuditDialog(rowObj);
            } else {
                openDetail(rowObj, '详情', 1)
            }
        });


        // 监听时间选择器控制选择框点击事件
        form.on('checkbox(datepicker)', function (data) {
            const $boxThat = $(data.elem);
            var boxTitle = $boxThat.attr('title');
            var dpIndex = -1;
            $boxThat.parent().find('input:checkbox').each(function (idx, obj) {
                if ($(obj).attr('title') == boxTitle) {
                    dpIndex = idx;
                }
            })
            var $dataPicker = $boxThat.closest('form')
                .find('.date-picker-item').eq(dpIndex);
            if (data.elem.checked) {
                $dataPicker.addClass('inline-block').find('input').attr('disabled', false);
            } else {
                $dataPicker.removeClass('inline-block').find('input').prop('disabled', true);
            }

            form.render();
        });

        // 监听查询表单提交事件
        form.on('submit(submit-search)', function (obj) {
            var params = getSearchParams(obj);

            if (!params) {
                return false;
            }

            searchForTable(params);
            return false;
        });

        // 监听行工具事件
        table.on('tool(zmn-work-table)', function (obj) {

            // 详情
            if (obj.event === 'detail') {
                openDetail(obj, '详情', 1)
            }

            // 审核
            if (obj.event === 'audit') {
                openAuditDialog(obj);
            }
        });

        // 工具栏
        table.on('toolbar(zmn-work-table)', function (obj) {
            switch (obj.event) {
                case 'exports': // 导出
                    $('#submit-export').trigger('click');
                    break;
            }
        });

        // 监听查询表单导出事件
        form.on('submit(submit-export)', function (obj) {
            $("#submit-export").addClass("layui-btn-disabled").attr("disabled", true);
            setTimeout(function () {
                $("#submit-export").removeClass("layui-btn-disabled").removeAttr("disabled");
            }, 10000);

            var params = getSearchParams(obj);
            if (!params) {
                return false;
            }

            layer.tips('至多导出 10000 条', obj.elem, {
                success: function () {
                    $.ajax({
                        type: 'POST',
                        url: OMS_BASE_URL + '/work/redistribute/list/export/async.action',
                        contentType: 'application/json; charset=utf-8',
                        data: JSON.stringify(params),
                        async: false,
                        dataType: 'json',
                        success: function (res) {
                            if (res.status == 200) {
                                top.layui.index.openTabsPage(config.elephantHost + '/tapi/export/list.action', "导出文件管理");
                            } else {
                                layer.msg(res.message, {icon: 2});
                            }
                        },
                        error: function (res) {
                            layer.msg('操作发生异常，请重试', {icon: 5});
                        }
                    });
                }
            });

            return false;
        });
    }

    /**
     * 检查 某个id 是否存在DOM元素中
     *
     * @param id
     * @returns {boolean}
     */
    function checkExistId(id) {
        let $id = $('#' + id);
        return $id.length > 0;
    }

    /**
     * 清空指定元素的下拉框内容
     *
     * @param selectId
     */
    function clearZmnSelectedValue(selectId) {
        try {
            let select = zmnSelect.getXmSelect(selectId);
            if (select && zmnUtil.isObject(select) && zmnUtil.isFunction(select.setValue)) {
                select.setValue([]);
            }
        } catch (e) {
        }
    }

    /**
     * 渲染日期选择器
     * @param selector 日期选择器的选择器或者 Dom 对象
     */
    function renderDatePicker(selector) {
        var config = {
            elem: selector,
            format: selector.indexOf('Start') !== -1 ? 'yyyy-MM-dd' : 'yyyy-MM-dd'
        };
        laydate.render(config);
    }

    /**
     * 初始化页面的所有日期组件
     */
    function initALLDatePickers() {
        $.each(datePickerSelectorArray, function (index, keyword) {
            $.each(['Start', 'End'], function (i, suffix) {

                renderDatePicker('#' + keyword + suffix);
            });
        });
    }

    /**
     * 初始化警示提示框
     */
    var initWarningHoverTips = function (btn) {
        var $triggers = btn ? $(btn) : $('.warning').closest('td');

        $triggers.tooltipster({
            content: 'Loading...',
            side: 'right',
            theme: 'tooltipster-layui',
            maxWidth: 930,
            interactive: true,
            contentAsHTML: true,
            updateAnimation: 'null',
            functionBefore: function (instance, helper) {
                var $origin = $(helper.origin);
                var contentHtml = $origin.find('.warning-content').html();

                instance.content(contentHtml);
            }
        });
    };

    /**
     * 渲染表格
     * @param {object} params 查询参数
     * @param {array} data 表格数据
     * @returns {object}
     */
    function renderTable(params) {
        var tableCols = table.getConfig('zmn-work-table').cols;

        table.render({
            id: 'zmn-work-table',
            elem: '#zmn-work-table',
            method: 'POST',
            contentType: 'application/json;charset=utf-8',
            toolbar: '#toolbar',
            url: LIST_REDISTRIBUTE_INFO_URL,
            defaultToolbar: defaultToolbar,
            limit: 100,
            limits: [100],
            loading: true,
            page: true,
            cols: tableCols,
            where: {
                ...params
            },
            request: {
                pageName: 'pageIndex', // 页码
                limitName: 'pageSize' // 条数限制
            },
            response: {
                statusCode: 200 // 重新规定成功的状态码为 200，table 组件默认为 0
            },
            parseData: function (res) {
                var count = res.data ? res.data.count : 0;

                if (count > 0) {
                    $('#precise-count').text('（共 ' + count + ' 条）');
                } else {
                    $('#precise-count').text('');
                }


                $('.layui-this').find('.count').text('（共 ' + count + ' 条）');

                return {
                    "code": res.status, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.data ? (res.data.count > 10000 ? 10000 : res.data.count) : 0, //解析数据长度
                    "data": res.data ? res.data.data : [] //解析数据列表
                };
            },
            done: function (res, curr, count) {
                let data = res.data;

                // 打是否可以审核标记
                data.forEach(data => setOperationButtonFlags(data))

                window.dataList = data;
                initWarningHoverTips()
            }
        })
    }

    /**
     * 搜索框搜索方法
     * @param {object} params 查询参数
     * @param data
     */
    function searchForTable(params) {
        renderTable(params);
    }


    /**
     * 初始化页面所有下拉框
     */
    function initAllSelect() {

        // 公司&服务商 单选
        if (checkExistId('companyIdOrGridCompanyIdList')) {
            zmnSelect.selectlSubCompaniesCity({
                subCompanySelectId: 'companyIdOrGridCompanyIdList',
                spCompanySelectId: 'manageCompanyIdOrGridManageCompanyId',
            }, {
                subCompanySelectId: {
                    isRadio: false,
                    remote: {
                        limitPermit: json.vo.orgLimitPermit,
                        events: {
                            extendParams: function () {
                                return {plat: plat}
                            }
                        }
                    },
                    events: {
                        changed: function (values) {
                            json.vo.companyIdOrGirdCompanyIdList = values;
                        }
                    }
                },
                spCompanySelectId: {
                    isRadio: true,
                    remote: {
                        limitPermit: false,
                        events: {
                            extendParams: function () {
                                return {
                                    plat: plat,
                                    pageSize: 10000
                                }
                            }
                        }
                    },
                    events: {
                        changed: function (values) {
                            json.vo.spCompanyOrGridSpCompanyIdIdList = values;
                        }
                    }
                }
            });
        }

        // 公司&执行服务商 单选
        if (checkExistId('companyIdList')) {
            zmnSelect.selectlSubCompaniesCity({
                subCompanySelectId: 'companyIdList',
                spCompanySelectId: 'manageCompanyId',
            }, {
                subCompanySelectId: {
                    isRadio: false,
                    remote: {
                        limitPermit: json.vo.orgLimitPermit,
                        events: {
                            extendParams: function () {
                                return {plat: plat}
                            }
                        }
                    },
                    events: {
                        changed: function (values) {
                            json.vo.companyIdList = values;
                            json.vo.companyId = zmnUtil.isArray(values) && values.length > 0 ? values[0] : null;
                        }
                    }
                },
                spCompanySelectId: {
                    isRadio: true,
                    remote: {
                        limitPermit: false,
                        events: {
                            extendParams: function () {
                                return {
                                    plat: plat,
                                    pageSize: 10000
                                }
                            }
                        }
                    },
                    events: {
                        changed: function (values) {
                            json.vo.spCompanyIdList = values;
                            json.vo.spCompanyId = zmnUtil.isArray(values) && values.length > 0 ? values[0] : null;
                        }
                    }
                }
            });
        }

        // 改派状态 多选
        if (checkExistId('redistributeStatusList')) {
            selectRedistributeStatus('redistributeStatusList')
        }

        // 审核状态 多选
        if (checkExistId('auditStatusList')) {
            selectAuditStatus('auditStatusList')
        }

        // 求助状态 多选
        if (checkExistId('helpStatusList')) {
            selectHelpStatus('helpStatusList')
        }

        // 行政服务商 单选
        if (checkExistId('gridCompanyIdList')) {
            zmnSelect.selectlSubCompaniesCity({
                subCompanySelectId: 'gridCompanyIdList',
                spCompanySelectId: 'gridManageCompanyId',
            }, {
                subCompanySelectId: {
                    isRadio: false,
                    remote: {
                        limitPermit: json.vo.orgLimitPermit,
                        events: {
                            extendParams: function () {
                                return {plat: plat}
                            }
                        }
                    },
                    events: {
                        changed: function (values) {
                            json.vo.gridCompanyIdList = values;
                            json.vo.gridCompanyId = zmnUtil.isArray(values) && values.length > 0 ? values[0] : null;
                        }
                    }
                },
                spCompanySelectId: {
                    isRadio: true,
                    remote: {
                        limitPermit: false,
                        events: {
                            extendParams: function () {
                                return {
                                    plat: plat,
                                    pageSize: 10000
                                }
                            }
                        }
                    },
                    events: {
                        changed: function (values) {
                            json.vo.gridSpCompanyIdList = values;
                            json.vo.gridSpCompanyId = zmnUtil.isArray(values) && values.length > 0 ? values[0] : null;
                        }
                    }
                }
            });
        }

        // 公司&服务商 多选
        if (checkExistId('companyIdOrGridCompanyIdList')) {
            zmnSelect.selectlSubCompaniesCity({
                subCompanySelectId: 'companyIdOrGridCompanyIdList',
                spCompanySelectId: 'manageCompanyIdOrGridManageCompanyIdList',
            }, {
                subCompanySelectId: {
                    isRadio: false,
                    remote: {
                        limitPermit: json.vo.orgLimitPermit,
                        events: {
                            extendParams: function () {
                                return {
                                    plat: plat
                                }
                            }
                        }
                    },
                    events: {
                        changed: function (values) {
                            json.vo.companyIdOrGirdCompanyIdList = values;
                        }
                    }
                },
                spCompanySelectId: {
                    isRadio: false,
                    remote: {
                        limitPermit: false,
                        events: {
                            extendParams: function () {
                                return {
                                    plat: plat,
                                    pageSize: 10000
                                }
                            }
                        }
                    },
                    events: {
                        changed: function (values) {
                            json.vo.spCompanyOrGridSpCompanyIdIdList = values;
                        }
                    }
                }
            });
        }

        // 公司&执行服务商 多选
        if (checkExistId('companyIdList')) {
            zmnSelect.selectlSubCompaniesCity({
                subCompanySelectId: 'companyIdList',
                spCompanySelectId: 'manageCompanyIdList',
            }, {
                subCompanySelectId: {
                    isRadio: false,
                    remote: {
                        limitPermit: json.vo.orgLimitPermit,
                        events: {
                            extendParams: function () {
                                return {plat: plat}
                            }
                        }
                    },
                    events: {
                        changed: function (values) {
                            json.vo.companyIdList = values;
                            json.vo.companyId = zmnUtil.isArray(values) && values.length > 0 ? values[0] : null;
                        }
                    }
                },
                spCompanySelectId: {
                    isRadio: false,
                    remote: {
                        limitPermit: false,
                        events: {
                            extendParams: function () {
                                return {
                                    plat: plat,
                                    pageSize: 10000
                                }
                            }
                        }
                    },
                    events: {
                        changed: function (values) {
                            json.vo.spCompanyIdList = values;
                            json.vo.spCompanyId = zmnUtil.isArray(values) && values.length > 0 ? values[0] : null;
                        }
                    }
                }
            });
        }

        // 行政服务商 多选
        if (checkExistId('gridCompanyIdList')) {
            zmnSelect.selectlSubCompaniesCity({
                subCompanySelectId: 'gridCompanyIdList',
                spCompanySelectId: 'gridManageCompanyIdList',
            }, {
                subCompanySelectId: {
                    isRadio: false,
                    remote: {
                        limitPermit: json.vo.orgLimitPermit,
                        events: {
                            extendParams: function () {
                                return {plat: plat}
                            }
                        }
                    },
                    events: {
                        changed: function (values) {
                            json.vo.gridCompanyIdList = values;
                            json.vo.gridCompanyId = zmnUtil.isArray(values) && values.length > 0 ? values[0] : null;
                        }
                    }
                },
                spCompanySelectId: {
                    isRadio: false,
                    remote: {
                        limitPermit: false,
                        events: {
                            extendParams: function () {
                                return {
                                    plat: plat,
                                    pageSize: 10000
                                }
                            }
                        }
                    },
                    events: {
                        changed: function (values) {
                            json.vo.gridSpCompanyIdList = values;
                            json.vo.gridSpCompanyId = zmnUtil.isArray(values) && values.length > 0 ? values[0] : null;
                        }
                    }
                }
            });
        }

        // 省份、城市、区域
        if (checkExistId('provinceIdList')) {
            zmnSelect.selectlAreas({
                provinceSelectId: 'provinceIdList',
                citySelectId: 'cityIdList',
                countySelectId: checkExistId('countyIdList') ? 'countyIdList' : null,
            }, {
                provinceSelectId: {
                    isRadio: false,
                    events: {
                        changed: function (values) {
                            if (values.length == 0) {
                                // 默认加载 城市
                                zmnSelect.reloadXmSelect('cityIdList', {
                                    tips: "-选择城市-",
                                    isReload: true
                                });
                            }
                        }
                    }
                },
                citySelectId: {
                    isRadio: false,
                    events: {
                        changed: function (values) {
                            // 查询网格列表
                            zmnOmsSelect.reloadXmSelect('gridIdList');
                        }
                    }
                },
                countySelectId: {
                    isRadio: false
                },
            });

            // 默认加载 城市
            zmnSelect.reloadXmSelect('cityIdList', {
                tips: "-选择城市-",
                isReload: true
            });
        } else if (checkExistId('cityIdList')) {
            zmnSelect.selectCity('cityIdList', {
                tips: "-选择城市-",
                isReload: true
            });
        }

        // 服务分类
        if (checkExistId('servCategId')) {
            zmnSelect.selectServCategory('servCategId', {
                tips: "-选择服务分类-",
                isReload: true,
                events: {
                    changed(values) {
                        json.vo.servCategId = zmnUtil.isArray(values) && values.length > 0 ? values[0] : null;

                        if (checkExistId('showProductIdList')) {
                            zmnOmsSelect.reloadXmSelect('showProductIdList', {
                                remote: {
                                    events: {
                                        extendParams: function () {
                                            let data = {
                                                servCategoryId: json.vo.servCategId,
                                                categIds: json.vo.categTwoIdList,
                                            }
                                            return {body: data};
                                        }
                                    }
                                }
                            });
                        }

                        if (checkExistId('productIdList')) {
                            zmnOmsSelect.reloadXmSelect('productIdList', {
                                remote: {
                                    events: {
                                        extendParams: function () {
                                            let data = {
                                                servCategoryId: json.vo.servCategId,
                                                categIds: json.vo.categTwoIdList,
                                            }
                                            return {body: data};
                                        }
                                    }
                                }
                            });
                        }
                    }
                }
            });
        }

        // 业务分类、产品分组
        if (checkExistId('bizType') && checkExistId('servProductGroupIdList')) {
            zmnSelect.selectlServBizTypeGroup({
                bizTypeSelectId: 'bizType',
                prodGroupSelectId: 'servProductGroupIdList',
            }, {
                bizTypeSelectId: {
                    selectedValues: json.vo.bizType == null ? null : json.vo.bizType,
                    isRadio: true,
                    events: {
                        changed(values) {
                            json.vo.bizType = zmnUtil.isArray(values) && values.length > 0 ? values[0] : null;
                        }
                    }
                },
                prodGroupSelectId: {
                    events: {
                        changed(values) {
                        }
                    }
                },
            });
        }

        if (checkExistId('bizLineList')) {
            zmnSelect.selectlServBizUnits({
                // bizTypeSelectId: 'bizType',
                bizLineSelectId: 'bizLineList',
            }, null);
        }

        // 前台一二级分类
        if (checkExistId('showCategOneIdList')) {
            zmnSelect.selectlEcProdCategories({
                ecCategOneSelectId: 'showCategOneIdList',
                ecCategTwoSelectId: 'showCategTwoIdList',
            }, {
                ecCategOneSelectId: {
                    tips: "-前台一级分类-",
                    isReload: true,
                },
                ecCategTwoSelectId: {
                    tips: "-前台二级分类-",
                    events: {
                        changed(values) {
                            json.vo.showCategTwoIdList = values;
                            zmnOmsSelect.reloadXmSelect('showProductIdList', {
                                remote: {
                                    events: {
                                        extendParams: function () {
                                            let data = {
                                                servCategoryId: json.vo.servCategId,
                                                categIds: json.vo.showCategTwoIdList
                                            }
                                            return {body: data};
                                        }
                                    }
                                }
                            });
                        }
                    }

                }
            });
        }

        // 前台产品
        if (checkExistId('showProductIdList')) {
            zmnOmsSelect.selectProductList('showProductIdList', {
                tips: "-选择前台产品-",
                remote: {
                    events: {
                        extendParams: function () {
                            return {
                                showType: 2
                            };
                        }
                    }
                }
            });
        }

        // 后台一二级分类
        if (checkExistId('categOneIdList')) {
            zmnSelect.selectlErpProdCategories({
                erpCategOneSelectId: 'categOneIdList',
                erpCategTwoSelectId: 'categTwoIdList',
            }, {
                erpCategOneSelectId: {
                    tips: "-后台一级分类-",
                    isReload: true,
                },
                erpCategTwoSelectId: {
                    tips: "-后台二级分类-",
                    events: {
                        changed(values) {
                            json.vo.categTwoIdList = values;
                            zmnOmsSelect.reloadXmSelect('productIdList', {
                                remote: {
                                    events: {
                                        extendParams: function () {
                                            let data = {
                                                servCategoryId: json.vo.servCategId,
                                                categIds: json.vo.categTwoIdList,
                                            }
                                            return {body: data};
                                        }
                                    }
                                }
                            });
                        }
                    }
                }
            });
        }

        // 后台产品
        if (checkExistId('productIdList')) {
            zmnOmsSelect.selectProductList('productIdList', {
                tips: "-选择后台产品-",
                remote: {
                    events: {
                        extendParams: function () {
                            return {
                                showType: 1
                            };
                        }
                    }
                }
            });
        }

        // 工程师
        if (checkExistId('masterIds')) {
            zmnSelect.searchEngineer('masterIds', {
                remote: {
                    limitPermit: json.vo.orgLimitPermit,
                    events: {
                        extendParams: function () {
                            return {
                                plat: plat,
                                companyId: json.vo.companyId,
                                spCompanyId: json.vo.spCompanyId,
                            }
                        }
                    }
                },
                events: {
                    changed: function (values) {
                    }
                }
            });
        }

        // 改派缘由
        if (checkExistId('reasonIdList')) {
            zmnOmsSelect.searchConfRedistributeReason('reasonIdList', {
                tips: "全部",   //默认提示
                type: 1,
                page: {
                    enable: true,
                    remote: true,
                    pageSize: 20
                },
            });
        }

        // 下单渠道
        if (checkExistId('channelTwoIdList')) {
            zmnSelect.selectlChannels({
                channelOneSelectId: 'channelTwoIdList',
                channelTwoSelectId: 'channelIdList',
            }, {
                channelOneSelectId: {
                    remote: {
                        limitPermit: json.vo.channelLimitPermit,
                    },
                    events: {
                        changed: function (values) {
                            if (values.length == 0) {
                                zmnSelect.reloadXmSelect('channelIdList', {
                                    isReload: true
                                });
                            }
                        }
                    }
                },
                channelTwoSelectId: {
                    remote: {
                        limitPermit: json.vo.channelLimitPermit,
                    }
                }
            });
            zmnSelect.reloadXmSelect('channelIdList', {
                isReload: true
            });
        } else if (checkExistId('channelIdList')) {
            zmnSelect.searchChannel('channelIdList', {
                remote: {
                    limitPermit: json.vo.channelLimitPermit,
                    events: {
                        extendParams: function () {
                            return {
                                "rank": 2, // 渠道层级：Integer类型；1-查询一级渠道，2-查询二级渠道,null不限
                            }
                        }
                    }
                },
                events: {
                    changed: function (values) {
                    }
                }
            });
        }

        // 工单结果
        zmnOmsSelect.selectWorkResultStatus('workResultStatus');
        // 工单状态
        zmnOmsSelect.selectWorkStatus('workStatusList');
        // 工单类型
        zmnOmsSelect.selectWorkType('workTypeList');
        // 工单标记
        zmnOmsSelect.selectOrderWorkTagList('tagIdList');
        // 支付状态
        zmnOmsSelect.selectOrderPayStatus('payStatusList');
        zmnOmsSelect.selectOrderPayStatus('payStatusList');

        // 审核人
        if (checkExistId('auditerId')) {
            zmnSelect.searchStaff('auditerId', {
                isRadio: true,
                remote: {
                    limitPermit: json.vo.orgLimitPermit,
                    events: {
                        extendParams: function () {
                            return {
                                companyIdList: json.vo.companyIdList,
                            }
                        }
                    }
                }
            });
        }
    }


    /**
     * 初始化页面
     */
    function initPage() {
        // 初始化页面所有下拉框
        initAllSelect();

        // 初始化表单验证器
        initFormVerify();

        // 初始化初次请求参数
        initRequestParams();

        // 渲染 table
        if (tableConfig.initialSearch) {
            searchForTable(tableConfig.defaultParams);
        } else {
            searchForTable({});
        }

        // 初始化事件
        initEvent();
    }

    initPage();
    exports('oms_redistribute_list');
});
